package com.KKd.controller;

import com.KKd.pojo.Books;
import com.KKd.service.BookService;
import com.KKd.service.BookServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.awt.ModalExclude;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 14587
 * @date 2020/11/5 18:19
 */
@Controller
@RequestMapping("/book")
public class BookController {
    //controller层就是调用service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookServiceImpl bookService;

    //查询全部书籍,返回一个书籍展示页面
    @RequestMapping("/allBooks")
    public String listBooks(Model model){
        List<Books> books = bookService.queryAllBooks();
        model.addAttribute("books",books);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBookPage")
    public String toAddBookPage()
    {
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook"+books);
        bookService.addBook(books);
        return "redirect:/book/allBooks";//重定向到一个请求
    }

    //跳转到修改页面
    @RequestMapping("/toUpdatePage")
    public String toUpdatePage(int id, Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("Qbooks",books);
        return "updateBook";
    }
    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        return "redirect:/book/allBooks";
    }
    //删除书籍
    @RequestMapping("/deleteBook")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBooks";
    }
    //查询书籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName, Model model){
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(books);
        if (books==null){
            list=bookService.queryAllBooks();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("books",list);
        return "allBook";
    }
}
